package org.discala.samples.complex.recipegenerator

import org.discala.samples.complex.domain.Ingredient
import java.net.URL
import scala.io.Source
import scala.util.Random

/**
 * @author Chris Turner
 */
private[recipegenerator] trait IngredientFactoryComponent {

  this: AnyRef { val sourcePath: () => String } =>

  val factory: () => IngredientFactory

  class FileSourceIngredientFactory extends IngredientFactory {

    val LinePattern = """([A-Za-z\-\s]+),([01]\.[0-9]+),([01]\.[0-9]+)[\n]?""".r
    val allIngredients = loadIngredients()
    val random = new Random

    def ingredient() = {
      random.synchronized {
        allIngredients(random.nextInt(allIngredients.length))
      }
    }

    private[this] def loadIngredients() = {
      var ingredients = List[Ingredient]()
      Source.fromURL(fromClasspath(sourcePath())).getLines.foreach { line =>
        line match {
          case LinePattern(name, aroma, taste) =>
            ingredients = new Ingredient(name, aroma.toFloat, taste.toFloat) :: ingredients
          case _ => throw new IllegalIngredientException(line)
        }
      }
      ingredients.toArray
    }

    private[this] def fromClasspath(resourceName: String): URL = {
      val resourceUrl = getClass.getClassLoader.getResource(resourceName)
      require(resourceUrl != null)
      resourceUrl
    }
  }
}
